#!.venv\Scripts\python3.exe
# -*- encoding: utf-8 -*-
'''
@File    :   main.py
@Time    :   2020/08/13 21:47:23
@Author  :   ZC 
@Version :   1.0
@Contact :   869194258@qq.com
'''
# Start typing your code from here

import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import A4
import reportlab.pdfbase.ttfonts
reportlab.pdfbase.pdfmetrics.registerFont(
    reportlab.pdfbase.ttfonts.TTFont('方正粗黑宋简体', 'fonts\\方正粗黑宋简体.ttf'))
import reportlab.lib.fonts
from PyQt5 import QtCore, QtWidgets
from qt import mainwindow
import sys
from enum import Enum
import os
import time


def drawTianItem(c, x, y, pertiansidelength,drawtype):
    c.setDash([], 0)
    c.rect(x, y, pertiansidelength, pertiansidelength, fill=1)
    c.setDash([1, 2, 1, 2], 0)
    c.line((x + pertiansidelength / 2), y, (x + pertiansidelength / 2),
           (y + pertiansidelength))
    c.line(x, (y + pertiansidelength / 2), (x + pertiansidelength),
           (y + pertiansidelength / 2))
    if drawtype == DrawType.DRAW_MI:
        c.line(x , y, (x + pertiansidelength),
            (y + pertiansidelength))
        c.line(x, (y + pertiansidelength), (x + pertiansidelength),
            y)


def drawTian(c, width, height, percolumnnum, perpagerow, drawtype):
    #每个田子格的边长
    pertiansidelength = (width / percolumnnum)
    #每行间距
    perrowmargin = ((height - (perpagerow * pertiansidelength)) /
                    (perpagerow - 1))
    for row in range(perpagerow):
        for column in range(percolumnnum):
            x = row * (perrowmargin + pertiansidelength)
            y = column * pertiansidelength
            drawTianItem(c, x, y, pertiansidelength,drawtype)


def processTian(c):
    ##############################################
    # 每行个数
    percolumnnum = 12
    # 每页多少行
    perpagerow = 13
    #左右单边距离
    lrmargin = 0.5 * inch
    #顶部底部边距
    tbmargin = 0.5 * inch

    drawTian(c, A4[0] - 2 * lrmargin, A4[1] - 2 * tbmargin, percolumnnum,
             perpagerow,DrawType.DRAW_TIAN)
    ################################################


def processMi(c):
    ##############################################
    # 每行个数
    percolumnnum = 12
    # 每页多少行
    perpagerow = 13
    #左右单边距离
    lrmargin = 0.5 * inch
    #顶部底部边距
    tbmargin = 0.5 * inch

    drawTian(c, A4[0] - 2 * lrmargin, A4[1] - 2 * tbmargin, percolumnnum,
             perpagerow,DrawType.DRAW_MI)
    ################################################

def drawPinYinItem(c, x, width, height):
    perheight = height / 3
    for row in range(4):
        if row == 0 or row == 3:
            c.setDash([], 0)
        else:
            c.setDash([1, 2, 1, 2], 0)
        c.line(x + row * perheight, 0, x + row * perheight, width)


def drawPinYin(c, width, height, perpagerow, perrowmargin):
    #每个拼音所占高度
    perpinyinheight = (height - ((perpagerow - 1) * perrowmargin)) / perpagerow
    for row in range(perpagerow):
        x = row * (perpinyinheight + perrowmargin)
        y = 0
        drawPinYinItem(c, x, width, perpinyinheight)


def processPinYin(c):
    # 每页多少行
    perpagerow = 21
    #左右单边距离
    lrmargin = 0.5 * inch
    #顶部底部边距
    tbmargin = 0.5 * inch
    #每行间距
    perrowmargin = 0.1 * inch
    drawPinYin(c, A4[0] - 2 * lrmargin, A4[1] - 2 * tbmargin, perpagerow,
               perrowmargin)


def drawPinYinAndTianItem(c, x, width, perPYTheight, percolumnnum):
    pinyinheight = perPYTheight / 2
    perpinyinheight = pinyinheight / 3
    #绘制拼音部分
    for row in range(3):
        if row == 0:
            c.setDash([], 0)
        else:
            c.setDash([1, 2, 1, 2], 0)
        c.line(x + row * perpinyinheight, 0, x + row * perpinyinheight, width)
    #绘制田子格部分
    startx = x + 3 * perpinyinheight
    #每个田子格的边长
    pertiansidelength = (width / percolumnnum)
    for column in range(percolumnnum):
        y = column * pertiansidelength
        drawTianItem(c, startx, y, pertiansidelength)


def drawPinYinAndTian(c, width, height, perpagerow, perrowmargin,
                      percolumnnum):
    #每个拼音和田子格组合的高度
    perPYTheight = (height - ((perpagerow - 1) * perrowmargin)) / perpagerow
    for row in range(perpagerow):
        x = row * (perPYTheight + perrowmargin)
        drawPinYinAndTianItem(c, x, width, perPYTheight, percolumnnum)


def processPinYinAndTian(c):
    # 每页多少行
    perpagerow = 10
    # 每行个数
    percolumnnum = 12
    #左右单边距离
    lrmargin = 0.5 * inch
    #顶部底部边距
    tbmargin = 0.5 * inch
    #每行间距
    perrowmargin = 0.3 * inch
    drawPinYinAndTian(c, A4[0] - 2 * lrmargin, A4[1] - 2 * tbmargin,
                      perpagerow, perrowmargin, percolumnnum)


def create_pdf(output, drawtype):
    now = datetime.datetime.today()
    date = now.strftime("%h %d %Y %H:%M:%S")
    c = canvas.Canvas(output, pagesize=A4)
    # define a large font
    c.setFont("方正粗黑宋简体", 14)
    c.setPageRotation(90)
    # move the origin up and to the left
    c.translate(0.5 * inch, 0.5 * inch)
    # choose some colors
    # c.setStrokeColorRGB(0.2, 0.5, 0.3)
    c.setStrokeColorRGB(0.2, 0, 0.3)
    c.setFillColorRGB(1, 1, 1)

    if drawtype == DrawType.DRAW_PINYIN:
        processPinYin(c)
    if drawtype == DrawType.DRAW_MI:
        processMi(c)
    if drawtype == DrawType.DRAW_TIAN:
        processTian(c)
    if drawtype == DrawType.DRAW_PINYINANDTIAN:
        processPinYinAndTian(c)

    c.showPage()
    c.save()
    time.sleep(1)
    TipMesage(MesageType.MT_Success)


# create_pdf()


class DrawType(Enum):
    DRAW_PINYIN = 1
    DRAW_TIAN = 2
    DRAW_PINYINANDTIAN = 3
    DRAW_MI = 4


class MesageType(Enum):
    MT_FILEUNDEFINE = 1
    MT_EXITFILE = 2
    MT_Success = 3


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = mainwindow.Ui_MainWindow()
    ui.setupUi(MainWindow)

    def onActionPinYin():
        print('OnActionPinYin')
        ret = checkResult()
        if ret['bcontinue']:
            create_pdf(ret['filepath'], DrawType.DRAW_PINYIN)
        else:
            TipMesage(ret['mesagetype'])

    def checkResult():
        #检查文件路径是否存在
        bselectdir = True
        selectedlabeltext = ui.selectedLabel.text().strip()
        if selectedlabeltext == '请指定文件保存路径':
            bselectdir = False
        #检查文件名是否存在
        bfilename = True
        filenameedittext = ui.textEdit.toPlainText()
        if filenameedittext == '':
            bfilename = False
        filepath = ''
        bcontinue = bfilename and bselectdir
        mesagetype = MesageType.MT_FILEUNDEFINE
        if bfilename and bselectdir:
            filepath = selectedlabeltext + '/' + filenameedittext + '.pdf'
            if os.path.exists(filepath):
                filepath = ''
                bcontinue = False
                mesagetype = MesageType.MT_EXITFILE
        ret = {
            'bcontinue': bcontinue,
            'filepath': filepath,
            'mesagetype': mesagetype
        }
        return ret

    def TipMesage(mesagetype):
        if mesagetype == MesageType.MT_FILEUNDEFINE:
            QtWidgets.QMessageBox.information(MainWindow, "提示", "文件目录或文件名未指定",
                                              QtWidgets.QMessageBox.Yes)
        if mesagetype == MesageType.MT_EXITFILE:
            QtWidgets.QMessageBox.information(MainWindow, "提示",
                                              "文件已存在，请修改文件名或路径",
                                              QtWidgets.QMessageBox.Yes)
        if mesagetype == MesageType.MT_Success:
            QtWidgets.QMessageBox.information(MainWindow, "提示", "生成成功",
                                              QtWidgets.QMessageBox.Yes)

    def onActionCloseBtn():
        print('onActionCloseBtn')
        sys.exit()

    def onActionSelectedBtn():
        print('onActionSelectedBtn')
        filename = QtWidgets.QFileDialog.getExistingDirectory()
        ui.selectedLabel.setText(filename)

    def onActionMiBtn():
        print('onActionMiBtn')
        ret = checkResult()
        if ret['bcontinue']:
            create_pdf(ret['filepath'], DrawType.DRAW_MI)
        else:
            TipMesage(ret['mesagetype'])

    def onActionTianBtn():
        print('onActionTianBtn')
        ret = checkResult()
        if ret['bcontinue']:
            create_pdf(ret['filepath'], DrawType.DRAW_TIAN)
        else:
            TipMesage(ret['mesagetype'])

    def onActionPinYinAndTianBtn():
        print('onActionPinYinAndTianBtn')
        ret = checkResult()
        if ret['bcontinue']:
            create_pdf(ret['filepath'], DrawType.DRAW_PINYINANDTIAN)
        else:
            TipMesage(ret['mesagetype'])

    def initClickedEvent():
        ui.closeBtn.clicked.connect(onActionCloseBtn)
        ui.selectedDirBtn.clicked.connect(onActionSelectedBtn)
        ui.pinYinBtn.clicked.connect(onActionPinYin)
        ui.miBtn.clicked.connect(onActionMiBtn)
        ui.tianBtn.clicked.connect(onActionTianBtn)
        ui.pinYinAndTianBtn.clicked.connect(onActionPinYinAndTianBtn)

    initClickedEvent()

    MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)
    MainWindow.show()
    sys.exit(app.exec_())